package com.czk.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czk.common.constant.ProductConstant;
import com.czk.common.to.SkuHasStockVo;
import com.czk.common.to.SkuReduction;
import com.czk.common.to.SpuBoundTo;
import com.czk.common.to.es.SkuEsModel;
import com.czk.common.utils.PageUtils;
import com.czk.common.utils.Query;
import com.czk.common.utils.R;
import com.czk.gulimall.product.dao.SpuInfoDao;
import com.czk.gulimall.product.entity.*;
import com.czk.gulimall.product.feign.CouponFeignService;
import com.czk.gulimall.product.feign.SearchFeignService;
import com.czk.gulimall.product.feign.WareFeignService;
import com.czk.gulimall.product.service.*;
import com.czk.gulimall.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private ProductAttrValueService attrValueService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private WareFeignService wareFeignService;
    @Autowired
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        // 1 保存spu的基本信息 spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);
        // 设置没有的属性创建时间和更新时间
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);


        // 2 保存spu的描述图片 spu_info_desc
        List<String> decript = spuSaveVo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        // 设置商品id
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        // 拼接
        spuInfoDescEntity.setDecript(String.join(",", decript));
        // 保存
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);


        // 3 保存spu的图片集  spu_images
        // 拿到所有图片
        List<String> images = spuSaveVo.getImages();
        // 保存图片
        spuImagesService.saveImages(spuInfoEntity.getId(), images);


        // 4 保存spu的规格参数 pms_pruduct_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        // 转换
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(item -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setAttrId(item.getAttrId());
            AttrEntity attr = attrService.getById(item.getAttrId());
            // 设置名称
            valueEntity.setAttrName(attr.getAttrName());
            valueEntity.setAttrValue(item.getAttrValues());
            valueEntity.setQuickShow(item.getShowDesc());
            valueEntity.setSpuId(spuInfoEntity.getId());
            return valueEntity;
        }).collect(Collectors.toList());
        attrValueService.saveProductAttr(collect);


        // 5 保存spu对应的sku信息
        List<Skus> skus = spuSaveVo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach(item -> {
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                // 补齐缺少的值
                // 品牌id
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                // 分类id
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                //
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                String defaultImg = "";
                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                        break;
                    }
                }
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.saveSkuInfo(skuInfoEntity);
                // 拿到id
                Long skuId = skuInfoEntity.getSkuId();
                List<SkuImagesEntity> imageEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    // 设置关联的id
                    skuImagesEntity.setSkuId(skuId);
                    // 设置图片地址
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    // 设置默认图片
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                })
                        .filter(entity -> {
                            // 过滤空的链接
                            return !StringUtils.isEmpty(entity.getImgUrl());
                        })
                        .collect(Collectors.toList());
                // 保存图片
                skuImagesService.saveBatch(imageEntities);
                // 保存sku的销售信息
                List<Attr> attr = item.getAttr();
                if (attr != null && attr.size() > 0) {
                    List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(a -> {
                        SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
                        BeanUtils.copyProperties(a, attrValueEntity);
                        attrValueEntity.setSkuId(skuId);
                        return attrValueEntity;
                    }).collect(Collectors.toList());
                    // 5 sku的销售属性信息 pms_sku_sale_attr_value
                    skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
                }
                // 5 保存spu的积分信息
                Bounds bounds = spuSaveVo.getBounds();
                SpuBoundTo spuBoundTo = new SpuBoundTo();
                BeanUtils.copyProperties(bounds, spuBoundTo);
                spuBoundTo.setSpuId(spuInfoEntity.getId());
                couponFeignService.saveSpuBounds(spuBoundTo);
                // 5.4 sku的优惠、满减信息 gulimall_sms->sms
                SkuReduction skuReduction = new SkuReduction();
                BeanUtils.copyProperties(item, skuReduction);
                // 设置id
                skuReduction.setSkuId(spuInfoEntity.getId());
                // 保存
                if (skuReduction.getFullCount() <= 0 || skuReduction.getFullPrice().compareTo(new BigDecimal("0")) == 1) {
                    couponFeignService.saveSkuReduction(skuReduction);
                }
            });
        }


    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        // 拿到key
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((w) -> {
                // spu的id或名称
                w.eq("id", key).or().like("spu_name", key);
            });
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("publish_status", status);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 商品上架
     *
     * @param spuId
     */
    @Override
    public void up(Long spuId) {
        // 组装需要的数据
        List<SkuInfoEntity> skus = skuInfoService.getSkuBySpuId(spuId);
        // 当前sku的所有可以被用来检索的规格属性
        List<ProductAttrValueEntity> baseAttrs = attrValueService.baseAttrListforspu(spuId);
        // 拿到所有id
        List<Long> attrIds = baseAttrs.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());
        List<Long> searchAttrIds = attrService.selectSearchAttrs(attrIds);

        Set<Long> idSet = new HashSet<>(searchAttrIds);
        List<SkuEsModel.Attrs> attrsList = baseAttrs.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        })
                .map(item -> {
                    SkuEsModel.Attrs attrs1 = new SkuEsModel.Attrs();
                    BeanUtils.copyProperties(item, attrs1);
                    return attrs1;
                })
                .collect(Collectors.toList());
        List<Long> skuIds = skus.stream().map(item -> {
            return item.getSkuId();
        }).collect(Collectors.toList());

        Map<Long, Boolean> stockMap = null;
        try {
            List<SkuHasStockVo> skuHasStocks = wareFeignService.getSkuHasStock(skuIds);
            stockMap = skuHasStocks.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.isHasStock()));
        } catch (Exception e) {
            log.error("库存服务出现异常" + e);
        }
        // 封装sku信息
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> collect = skus.stream().map(sku -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            // 属性对拷
            BeanUtils.copyProperties(sku, skuEsModel);
            // skuPrice
            skuEsModel.setSkuPrice(sku.getPrice());
            // skuImg
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());
            //  hasStock  远程调用是否由库存
            if (finalStockMap == null) {
                skuEsModel.setHasStock(true);
            } else {
                skuEsModel.setHasStock(finalStockMap.get(sku.getSkuId()));
            }
            //   hotScore 0
            skuEsModel.setHotScore(0L);
            // brandName
            BrandEntity brandEntity = brandService.getById(skuEsModel.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            // brandImg
            skuEsModel.setBrandImg(brandEntity.getLogo());
            // catalogName
            CategoryEntity categoryEntity = categoryService.getById(skuEsModel.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());
            if (attrsList != null) {
                skuEsModel.setAttrs(attrsList);
            }
            return skuEsModel;
        }).collect(Collectors.toList());
        // 发送给es进行保存
        R r = searchFeignService.productStatusUp(collect);
        if (r.getCode() == 0) {
            // 远程调用成功
            // 修改spu状态
            this.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        } else {
            // 失败
            // todo 重试机制，接口幂等性
        }
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity skuInfoEntity = skuInfoService.getById(skuId);
        Long spuId = skuInfoEntity.getSpuId();
        SpuInfoEntity entity = getById(spuId);
        return entity;
    }

    private void updateSpuStatus(Long spuId, int code) {
        SpuInfoEntity spuInfoEntity = this.baseMapper.selectById(spuId);
        spuInfoEntity.setPublishStatus(code);
        spuInfoEntity.setUpdateTime(new Date());
        this.baseMapper.updateById(spuInfoEntity);
    }
}